1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use super::*;

/// A function type's linearities
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct FunctionalLinearity {
    /// The relationship between the function type and it's argument
    dependency: Dependency,
    /// The linearity of members of the function type, when being passed around
    linearity: Linearity,
    /// The usage of members of this function type, when being called
    call_usage: Usage,
}

impl FunctionalLinearity {
    /// A standard, used functional linearity
    pub const USED: FunctionalLinearity = FunctionalLinearity::covar(Usage::USED);
    /// A contradictory functional linearity
    pub const CONTRADICTION: FunctionalLinearity = FunctionalLinearity {
        dependency: Dependency::CONTRADICTION,
        linearity: Linearity::LINEAR,
        call_usage: Usage::CONSUMED,
    };
    /// Construct a covariant functional linearity from a given argument usage
    #[inline]
    pub const fn covar(arg_usage: Usage) -> FunctionalLinearity {
        FunctionalLinearity {
            dependency: Dependency::covar(arg_usage),
            linearity: Linearity::NONLINEAR,
            call_usage: Usage::OBSERVED,
        }
    }
    /// Try to construct a new functional linearity
    #[inline]
    pub const fn new(
        dependency: Dependency,
        linearity: Linearity,
        call_usage: Usage,
    ) -> FunctionalLinearity {
        let call_usage = call_usage.meet(linearity.max_usage());
        FunctionalLinearity {
            dependency,
            linearity,
            call_usage,
        }.unify_contr()
    }
    /// Get the functional linearity for an identity function with a given linearity
    #[inline]
    pub const fn id(linearity: Linearity) -> FunctionalLinearity {
        FunctionalLinearity {
            dependency: Dependency::covar(linearity.max_usage()),
            linearity,
            call_usage: Usage::OBSERVED,
        }
    }
    /// Get the functional linearity for a constant function with a given linearity
    #[inline]
    pub const fn const_fn(linearity: Linearity) -> FunctionalLinearity {
        FunctionalLinearity {
            dependency: Dependency::NULL,
            linearity,
            call_usage: linearity.max_usage(),
        }
    }
    /// Unify a contradiction in this functional linearity
    #[inline]
    const fn unify_contr(self) -> FunctionalLinearity {
        if self.dependency.relationship.is_contradiction() {
            FunctionalLinearity::CONTRADICTION
        } else {
            self
        }
    }
    /// Get the dependency of this functional linearity
    #[inline]
    pub const fn dependency(self) -> Dependency {
        self.dependency
    }
    /// Get the linearity of this functional linearity
    #[inline]
    pub const fn linearity(self) -> Linearity {
        self.linearity
    }
    /// Get the call usage of this functional linearity
    #[inline]
    pub const fn call_usage(self) -> Usage {
        self.call_usage
    }
    /// Get the maximum usage of this linearity
    #[inline]
    pub const fn max_usage(self) -> Usage {
        self.linearity.max_usage()
    }
    /// Take this linearity with respect to a given argument
    #[inline]
    pub fn of_arg(self, arg: &SymbolId) -> FunctionalLinearity {
        FunctionalLinearity {
            dependency: self.dependency.of(arg),
            ..self
        }
    }
    /// Try to compare this linearity with another
    #[inline]
    pub const fn const_cmp(self, other: FunctionalLinearity) -> Result<Ordering, Error> {
        let linearity_ord = if let Some(linearity_ord) = self.linearity.const_cmp(other.linearity) {
            linearity_ord
        } else {
            return Err(Error::IncompatibleTypeLinearity(
                self.linearity,
                other.linearity,
            ));
        };
        let call_ord = if let Some(call_ord) = self.call_usage.const_cmp(other.call_usage) {
            call_ord
        } else {
            return Err(Error::IncompatibleCallUsage(
                self.call_usage,
                other.call_usage,
            ));
        };
        let dependency_ord =
            if let Some(dependency_ord) = self.dependency.const_cmp(other.dependency) {
                dependency_ord.reverse()
            } else {
                return Err(Error::IncompatibleRelationships(
                    self.dependency.relationship,
                    other.dependency.relationship,
                ));
            };
        if let Some(ord) =
            lattice_ord_opt(lattice_ord(linearity_ord, call_ord), Some(dependency_ord))
        {
            Ok(ord)
        } else {
            Err(Error::IncompatibleLinearity(None))
        }
    }
    /// Iterate over all possible functional linearities dependencies
    #[inline]
    pub fn iter_all() -> impl Iterator<Item = FunctionalLinearity> {
        Dependency::iter_all()
            .map(move |dependency| {
                Linearity::LINEARITIES
                    .iter()
                    .copied()
                    .map(move |linearity| {
                        Usage::USAGES
                            .iter()
                            .copied()
                            .map(move |call_usage| FunctionalLinearity {
                                dependency,
                                linearity,
                                call_usage,
                            })
                    })
                    .flatten()
            })
            .flatten()
    }
}

impl PartialOrd for FunctionalLinearity {
    #[inline]
    fn partial_cmp(&self, other: &FunctionalLinearity) -> Option<Ordering> {
        self.const_cmp(*other).ok()
    }
}

/// A pi type
#[derive(Clone, Eq)]
pub struct Pi {
    /// The symbol being abstracted over
    arg: SymbolId,
    /// The result type of this function
    result: ValId,
    /// The linearity of this pi type
    linearity: FunctionalLinearity,
    /// The type of this function type (a universe)
    ty: ValId,
    /// The free variable set of this function type
    fv: SymbolSet,
    /// Whether this pi type's result type is independent of it's argument
    is_indep: bool,
    /// This pi type's (cached) hash-code
    code: u64,
}

impl Debug for Pi {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        if self.is_indep {
            write!(
                fmt,
                "Pi({:?} => {:?}, {:?})",
                self.arg.ty(),
                self.result,
                self.linearity
            )
        } else {
            fmt.debug_struct("Pi")
                .field("arg", &self.arg)
                .field("result", &self.result)
                .field("lin", &self.linearity)
                .finish()
        }
    }
}

impl PartialEq for Pi {
    fn eq(&self, other: &Pi) -> bool {
        if self.code != other.code
            || self.linearity != other.linearity
            || self.is_indep != other.is_indep
        {
            return false;
        }
        match self.is_indep {
            true => self.arg.ty() == other.arg.ty() && self.result == other.result,
            false => self.arg == other.arg && self.result == other.result,
        }
    }
}

impl Hash for Pi {
    #[inline]
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        if self.is_indep {
            self.arg.ty().hash(hasher)
        } else {
            self.arg.hash(hasher);
        }
        self.result.hash(hasher);
    }
}

impl Pi {
    /// Try to create a new dependent function type with a given linearity
    ///
    /// Returns an error if `result` is not a type.
    pub fn try_new(
        arg: SymbolId,
        result: ValId,
        linearity: FunctionalLinearity,
    ) -> Result<Pi, Error> {
        if !result.is_ty() {
            return Err(Error::NotAType);
        }
        let linearity = linearity.of_arg(&arg);
        let ty = SET.clone(); //TODO: fix this...
        let mut fv = arg.ty().fv().union(result.fv());
        let is_indep = fv.remove(&arg).is_none();
        let mut result = Pi {
            arg,
            result,
            fv,
            ty,
            is_indep,
            code: 0,
            linearity,
        };
        result.update_code();
        Ok(result)
    }
    /// Get the result type of this pi type
    pub fn result(&self) -> &ValId {
        &self.result
    }
    /// Get the argument this pi type is abstracted over
    pub fn arg(&self) -> &SymbolId {
        &self.arg
    }
    /// Get the argument type of this pi type
    ///
    /// Equivalent to `self.arg().ty()`
    pub fn arg_ty(&self) -> &ValId {
        self.arg.ty()
    }
    /// Construct a unary function type
    ///
    /// Returns an error if `ty` is not a type.
    pub fn unary(ty: ValId, linearity: FunctionalLinearity) -> Result<Pi, Error> {
        let arg = SymbolId::param(ty.clone())?;
        Self::try_new(arg, ty, linearity)
    }
    /// Construct a binary function type
    ///
    /// Returns an error if `ty` is not a type
    pub fn binary(ty: ValId, linearity: FunctionalLinearity) -> Result<Pi, Error> {
        let arg = SymbolId::param(ty.clone())?;
        let unary = Self::try_new(arg.clone(), ty, linearity)?.into_valid();
        Self::try_new(arg, unary, linearity)
    }
    /// Check whether this pi type's return type is independent from it's input value
    #[inline]
    pub fn is_indep(&self) -> bool {
        self.is_indep
    }
    /// Update the hash-code of this pi-type
    ///
    /// Should be a no-op for any publically accessible pi-type
    #[inline]
    fn update_code(&mut self) {
        let mut hasher = Self::get_hasher();
        let arg_code = if self.is_indep {
            self.arg.ty().code()
        } else {
            self.arg.code()
        };
        arg_code.hash(&mut hasher);
        self.result.hash(&mut hasher);
        self.code = hasher.finish();
    }
    /// Get the hasher used for pi types
    #[inline]
    pub fn get_hasher() -> AHasher {
        AHasher::new_with_keys(0, 1)
    }
    /// Check whether two pi-types are invariant-equal
    pub fn invar_eq(&self, other: &Pi) -> bool {
        match self.is_indep {
            true => self.arg.ty() == other.arg.ty() && self.result == other.result,
            false => self.arg == other.arg && self.result == other.result,
        }
    }
    /// Whether this pi type contains all values of another pi type, under a given variance
    #[inline]
    pub fn subtype_pi(&self, other: &Pi, variance: Variance) -> Result<Match, Error> {
        if variance == Contravariant {
            return other.subtype_pi(self, Covariant);
        }
        if variance == Bivariant {
            return self
                .subtype_pi(other, Covariant)
                .or_else(|_| other.subtype_pi(self, Covariant));
        }
        let linearity_cmp = self.linearity.const_cmp(other.linearity)?;
        if !variance.matches_ord(linearity_cmp) {
            return Err(Error::WrongLinearityOrder);
        }
        if self.invar_eq(other) {
            return Ok(Match::dependency(self.linearity.call_usage()));
        }
        unimplemented!()
    }
    /// Get the linearity of members of this function type
    #[inline]
    pub fn fun_lin(&self) -> FunctionalLinearity {
        self.linearity
    }
    /// Get the relationship between a call of a function of this type and this function
    #[inline]
    pub fn call_relationship(&self) -> Relationship {
        Relationship::dependency(self.linearity.call_usage())
    }
}

impl Value for Pi {
    #[inline]
    fn ty(&self) -> &ValId {
        &self.ty
    }
    #[inline]
    fn is_groupoid(&self) -> bool {
        false
    }
    #[inline]
    fn is_ty(&self) -> bool {
        true
    }
    #[inline]
    fn is_kind(&self) -> bool {
        false
    }
    #[inline]
    fn into_enum(self) -> ValueEnum {
        ValueEnum::Pi(self)
    }
    #[inline]
    fn fv(&self) -> &SymbolSet {
        &self.fv
    }
    #[inline]
    fn code(&self) -> u64 {
        self.code
    }
    fn contains(&self, other: &ValId) -> Result<Match, Error> {
        self.subtype(other.ty(), Covariant)
    }
    #[inline]
    fn subtype(&self, other: &ValId, variance: Variance) -> Result<Match, Error> {
        match other.as_enum() {
            ValueEnum::Pi(pi) => self.subtype_pi(pi, variance),
            _ => Err(Error::TypeMismatch),
        }
    }
    fn eval_in_ctx(&self, ctx: &mut EvalCtx) -> Option<ValId> {
        if ctx.is_empty() {
            // We always treat pi types as normalized, for now
            return None;
        }
        let new_arg = self.arg.new_in_ctx(ctx);
        let mut ctx_tmp;
        let (arg, ctx) = if let Some(arg) = new_arg {
            if self.is_indep() {
                (Some(arg), ctx)
            } else {
                ctx_tmp = ctx.added_unchecked(self.arg.clone(), arg.clone().into_valid())
                    .expect("Adding a new symbol with a guaranteed new definition always results in a change");
                (Some(arg), &mut ctx_tmp)
            }
        } else if let Some(removed) = ctx.removed(&self.arg) {
            ctx_tmp = removed;
            (None, &mut ctx_tmp)
        } else {
            (None, ctx)
        };
        let result = self.result().eval_in_ctx(ctx);
        let (arg, result) = match (arg, result) {
            (None, None) => return None,
            (Some(arg), None) => (arg, self.result.clone()),
            (None, Some(result)) => (self.arg.clone(), result),
            (Some(arg), Some(result)) => (arg, result),
        };
        let pi = Pi::try_new(arg, result, self.linearity)
            .expect("Substituted pi construction should never fail");
        Some(pi.into_valid())
    }
    fn apply_ty_in_ctx(&self, arg: &ValId, ctx: &mut EvalCtx) -> Result<Abstract, Error> {
        let mut ctx_tmp;
        let (match_, ctx_ref) = if !self.is_indep {
            let (match_, c) = ctx.added(self.arg.clone(), arg.clone())?;
            if let Some(c) = c {
                ctx_tmp = c;
                (match_, &mut ctx_tmp)
            } else {
                (match_, ctx)
            }
        } else {
            let match_ = self.arg.match_symbol(arg)?;
            (match_, ctx)
        };
        let ty = self
            .result
            .eval_in_ctx(ctx_ref)
            .unwrap_or_else(|| self.result.clone());
        let abs = Abstract {
            ty,
            constraints: match_.into_constraints(None, Some(arg.clone())),
            relationship: self.call_relationship(),
        };
        Ok(abs)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn functional_linearity_partial_ord() {
        for linearity in FunctionalLinearity::iter_all() {
            assert!(
                linearity <= FunctionalLinearity::CONTRADICTION,
                "{:#?} <= {:#?}",
                linearity,
                FunctionalLinearity::CONTRADICTION
            );
        }
    }
    #[test]
    fn basic_unary_bool_properties() {
        let unary = Pi::unary(Bool.into_valid(), FunctionalLinearity::USED)
            .unwrap()
            .into_valid();
        assert_eq!(
            unary.apply_ty(&*FALSE).unwrap(),
            Abstract::used(Bool.into_valid()).unwrap()
        );
        assert_eq!(unary.apply_ty(&*NAT), Err(Error::TypeMismatch));
        assert_eq!(unary.apply(&*TRUE), Err(Error::NotAFunctionType));
    }
}